package top.shaozuo.simple.configuration.microprofile.config.source;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取默认的配置文件，配置文件名称为 META-INF/microprofile-config.properties
 * 
 * @author shaozuo
 *
 */
public class FilePropertiesConfigSource implements ConfigSource {

    private static final Logger logger = LoggerFactory.getLogger(FilePropertiesConfigSource.class);

    private static final String PROPERTIES_NAME = "META-INF/microprofile-config.properties";

    private final Map<String, String> properties;

    public FilePropertiesConfigSource() {
        Properties propertiesInFile = loadProperties(PROPERTIES_NAME);
        Map<String, String> fileProperties = propertiesInFile.entrySet().stream().collect(Collectors
                .toMap(e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue())));
        this.properties = new HashMap<>(fileProperties);
    }

    @Override
    public Set<String> getPropertyNames() {
        return properties.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return properties.get(propertyName);
    }

    @Override
    public String getName() {
        return "Simple Config File Properties";
    }

    /**
     * 载入多个文件, 文件路径使用Spring Resource格式.
     */
    private Properties loadProperties(String... resourcesPaths) {
        Properties props = new Properties();
        ClassLoader loader = this.getClass().getClassLoader();
        for (String location : resourcesPaths) {
            logger.info("Loading properties file from:{}", location);
            try (InputStream is = loader.getResourceAsStream(PROPERTIES_NAME);) {
                if (is != null) {
                    props.load(is);
                }
            } catch (IOException ex) {
                logger.error("Could not load properties from path:{}, error : {}", location,
                        ex.getMessage());
            }
        }
        return props;
    }
}
